import type { Request, Response } from 'express';

import config from '@config/index';
import Resp from '@utils/response';
import { pathIsOk } from '@utils/tools';
import fs from 'fs';
import { join } from 'path';
import { z } from 'zod';

// 参数校验规则
export const validator = z.object({
  appId: z.string(),
  repoName: z.string(),
});
// api
export const api = async (req: Request, res: Response): Promise<Response> => {
  try {
    const { appId, repoName } = req.query as z.infer<typeof validator>;

    const appDir = join(config.dataPath, appId);
    const appDirOk = await pathIsOk(appDir);
    if (!appDirOk) {
      return Resp.error(res, 404, '应用目录不存在或不可访问');
    }

    const repoDir = join(appDir, repoName);
    const repoDirOk = await pathIsOk(repoDir);
    if (!repoDirOk) {
      return Resp.error(res, 404, '仓库目录不存在或不可访问');
    }

    // 页面目录
    const pagesDir = join(repoDir, 'src', 'views');
    const pagesDirOk = await pathIsOk(pagesDir);
    if (!pagesDirOk) {
      return Resp.error(res, 404, '页面目录不存在或不可访问');
    }
    // 页面目录下的每一个文件夹都表示一个页面，文件夹名称即页面名称
    // 获取页面列表
    const pagesListDir = await fs.promises.readdir(pagesDir, { withFileTypes: true });
    const pagesList = pagesListDir.map(page => page.name)
    // 返回成功响应
    return Resp.success(res, pagesList, '成功');
  } catch (error) {
    console.error(error);
    // 捕获并处理异常，按错误类型返回合适响应
    return Resp.catch(res, error);
  }
};
